<template>
  <div>
    <div class="item" v-for="(item, index) in arr" :key="item.id">
      <div
        class="inner"
        :class="item.showDeleteBtn ? 'btn-show' : ''"
        @touchstart="start"
        @touchmove="move"
        @touchend="end(index)"
      >
        <div @touchstart.stop="">
          <van-checkbox
            v-model="item.checked"
            shape="square"
            @change="changeOne"
          ></van-checkbox>
        </div>
        <van-card
          :price="item.price"
          :title="item.goodsname"
          :thumb="$pre + item.img"
        >
          <div slot="num">
            <van-button @touchstart.stop="sub(item.id, item.num)">-</van-button>
            {{ item.num }}
            <van-button type="primary" @touchstart.stop="add(item.id)"
              >+</van-button
            >
          </div>
        </van-card>
        <van-button type="danger" @touchstart.stop="del(item.id)"
          >删除</van-button
        >
      </div>
    </div>
    <van-empty v-if="arr.length === 0" description="暂无数据" />

    <!-- 提交栏  -->
    <van-submit-bar
      :price="allPrice * 100"
      button-text="提交订单"
      safe-area-inset-bottom
      @submit="onSubmit"
    >
      <van-checkbox v-model="allChecked" @click="changeAll"
        >全选</van-checkbox
      >
    </van-submit-bar>
  </div>
</template>

<script>
import { Toast, Dialog } from "vant";
import { reqGetShop, reqShopDel, reqShopEdit } from "../../http/api";
export default {
  data() {
    return { 
      allChecked: false,
      arr: [],
      isRequest: true, 
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    getList() {
      reqGetShop({
        uid: JSON.parse(localStorage.getItem("isLogin")).uid,
      }).then((res) => {
        if (res.data.code === 200) {
          // 列表请求执行完成，这个时候才允许用户再次点击- isRequest=true
          this.isRequest = true;
          var arr = res.data.list ? res.data.list : [];
          // 给每条数据添加一个showDeleteBtn 字段，代表删除按钮是否出现
          // 注意：先添加字段，再给this.arr 赋值，这样showDeleteBtn 才有set()+get（）
          arr.forEach((item) => {
            //删除的状态
            item.showDeleteBtn = false;
            // 每条数据选中的状态 checked=false

            let obj = this.arr.find((i) => i.id === item.id);
            item.checked = obj ? obj.checked : false;
          });

          this.arr = arr;
          this.allChecked =
            this.arr.length === 0
              ? false
              : this.arr.every((item) => item.checked);
        }
      });
    },
    //点了+
    add(id) {
      reqShopEdit({
        id: id,
        type: 2,
      }).then((res) => {
        if (res.data.code === 200) {
          this.getList();
        }
      });
    },
    sub(id, num) {
 
      if (this.isRequest) {
        if (num <= 1) {
          Toast("宝贝不能再少了");
          return;
        }
        this.isRequest = false;
        reqShopEdit({
          id: id,
          type: 1,
        }).then((res) => {
          if (res.data.code === 200) {
            this.getList();
          }
        });
      }
    },
    del(id) {
      Dialog.confirm({
        title: "删除提示",
        message: "你确定要删除吗？",
      })
        .then(() => {
          reqShopDel({
            id: id,
          }).then((res) => {
            if (res.data.code === 200) {
              Toast(res.data.msg);
              this.getList();
            }
          });
        })
        .catch(() => {});
    },
    start(e) {
      this.startX = e.touches[0].clientX;
      this.endX = 0; 
    },
    move(e) {
      this.endX = e.touches[0].clientX;
    },
    end(index) {
      if (this.endX === 0) {
        this.$router.push("/detail/" + this.arr[index].goodsid);
        return;
      }

      if (this.endX + 20 < this.startX) {
        this.arr[index].showDeleteBtn = true;
      }
      if (this.startX + 20 < this.endX) {
        this.arr[index].showDeleteBtn = false;
      }
    },
    changeAll() {
      this.arr.forEach((item) => {
        item.checked = this.allChecked;
      });
    },
    changeOne() {
      this.allChecked = this.arr.every((item) => item.checked);
    },
    onSubmit() {
      // 存订单生成的时候需要的数据
      let json = {
        countmoney: this.allPrice,
        countnumber: this.arr.reduce(
          (val, item) => (item.checked ? val + item.num : val),
          0
        ),
        idstr:this.arr.reduce((val,item)=>item.checked?val+','+item.id:val,'').slice(1)
      };
      sessionStorage.setItem("orderInfo",JSON.stringify(json))
      this.$router.push("/order")
    },
  },
  computed: {
    allPrice() {
      return this.arr.reduce(
        (val, item) => (item.checked ? val + item.price * item.num : val),
        0
      );
    },
  },
};
</script>

<style scoped lang="less">
@import "../../less/index.less";
.item {
  width: 100vw;
  overflow: hidden;
  .inner {
    width: calc(100vw + 1rem);
    display: flex;
    transition: all 0.3s;
    height: 2rem;
    .van-checkbox {
      margin: @margin20;
    }
    .van-card {
      flex: 1;
    }
    .van-button {
      width: 1rem;
      height: 100% !important;
    }
  }
  .btn-show {
    margin-left: -1rem;
  }
}
.van-submit-bar {
  bottom: calc(@footerHeight + 0.01rem);
}
</style>